package thread;

import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-09-27
 * Time: 10:13
 */

class MyTimer {//定时器：这个线程是用来扫描队列，把元素放到阻塞队列里面
    private Thread t = null;
    Object locker = new Object();
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    //写一个方法去传输我们想要做到任务，让MyTimerTask去执行
    public void schedule(Runnable runnable , long delay){
      synchronized (locker){
          MyTimerTask task = new MyTimerTask(runnable , delay);
          queue.offer(task);
          locker.notify();
      }
    }
    public MyTimer(){
        t = new Thread(()->{
            try{
                while(true){
                    synchronized (locker){
                        while (queue.isEmpty()){
                            locker.wait();
                        }
                        MyTimerTask task = queue.peek();
                        if (System.currentTimeMillis() >= task.getTime()){
                            queue.poll();
                            task.run();
                        }else {
                            locker.wait(task.getTime() - System.currentTimeMillis());
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        });
        t.start();
    }


}
class MyTimerTask implements Comparable<MyTimerTask>{//定时器需要执行的任务，需要去构造这样的一个任务
    private long time;
    private Runnable runnable;
    public long getTime(){
        return time;
    }
    public MyTimerTask(Runnable runnable , long delay){
        this.time = System.currentTimeMillis() + delay;
        this.runnable = runnable;
    }
    public void run(){
        runnable.run();
    }
    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }


}
public class ThreadDemon33_3 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("第三次测试,等待的相对时间为三秒");
            }
        },3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("第一次测试,等待的相对时间为一秒");
            }
        },1000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("第二次测试,等待的相对时间为二秒");
            }
        },2000);
        System.out.println("hello main");
    }

}
